﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using BasePlatformNet;
using Newtonsoft.Json;
using BasePlatformCommon;

namespace L9SubSet
{
	public partial class Form_StartAddrMap : Form
	{
		private Form_MainSet parent = null;

		private bool initDone = false;

		// 回传参数
		private StartAddrMapPara startPara = null;

		private string section = "StartMap";			// 多语言文件配置节名称

		private string tip = "提示";						// MessageBox 题头

		/*****************************************************************************************/

		// 构造函数
		public Form_StartAddrMap(Form_MainSet parent, StartAddrMapPara startPara)
		{
			InitializeComponent();

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			this.Font = new System.Drawing.Font(this.Font.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

			this.parent = parent;
			this.startPara = startPara;

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}
		}

		// 设置本地化语言
		public void setLanguageText()
		{
			if (LanguageOper.available == false)
			{
				return;
			}

			LanguageOper.SetCurrentCulture();

			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 界面控件文字
			this.Text = LanguageOper.ReadValue(section, "startMap.Text");
			paraGroupBox.Text = LanguageOper.ReadValue(section, "paraGroupBox.Text");
			lwfLabel.Text = LanguageOper.ReadValue(section, "lwfLabel.Text");
			selectButton.Text = LanguageOper.ReadValue(section, "selectButton.Text");
			okButton.Text = LanguageOper.ReadValue(section, "okButton.Text");
			cancelButton.Text = LanguageOper.ReadValue(section, "cancelButton.Text");
		}

		// 选择布线文件
		private void selectButton_Click(object sender, EventArgs e)
		{
			OpenFileDialog o = new OpenFileDialog();
			if (lwfRadioButton.Checked)
			{
				startPara.fileType = "lwf";
				o.Filter = "Lwf Files(*.lwf)|*.lwf";
			}
			else if (jsonRadioButton.Checked)
			{
				startPara.fileType = "json";
				o.Filter = "Json Files(*.json)|*.json";
			}
			else if (dxfRadioButton.Checked)
			{
				startPara.fileType = "dxf";
				o.Filter = "Dxf Files(*.dxf)|*.dxf";
			}
			o.FilterIndex = 1;
			o.Multiselect = false;
			if (Directory.Exists(parent.lastPath_StartAddrMap_AddrMapFile))
			{
				o.InitialDirectory = parent.lastPath_StartAddrMap_AddrMapFile;
			}
			else
			{
				o.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
			}
			if (o.ShowDialog() == DialogResult.OK)
			{
				if (lwfRadioButton.Checked)
				{
					bool res = preReadLwfFile(o.FileName);
					if (res == false)
					{
						string msg = string.Format("布线文件 {0} 格式错误, 请检查", o.FileName);
						if (LanguageOper.available == true)
						{
							msg = string.Format(LanguageOper.ReadValue(section, "msgStr.0"), o.FileName);
						}

						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						return;
					}
				}

				if (jsonRadioButton.Checked)
				{
					bool res = preReadJsonFile(o.FileName);
					if (res == false)
					{
						string msg = string.Format("布线文件 {0} 格式错误, 请检查", o.FileName);
						if (LanguageOper.available == true)
						{
							msg = string.Format(LanguageOper.ReadValue(section, "msgStr.0"), o.FileName);
						}

						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						return;
					}
				}

				string filePath = o.FileName;
				filePathTextBox.Text = filePath;
				filePathTextBox.SelectionStart = filePathTextBox.Text.Length;
				filePathTextBox.ScrollToCaret();
				startPara.filePath = filePath;

				parent.lastPath_StartAddrMap_AddrMapFile = (new FileInfo(o.FileName)).DirectoryName;
			}
		}

		// Lwf 格式
		private void lwfRadioButton_CheckedChanged(object sender, EventArgs e)
		{
			if (initDone && lwfRadioButton.Checked)
			{
				filePathTextBox.Text = "";
				startPara.fileType = "lwf";
				selectButton.PerformClick();
			}
		}

		// Json 格式
		private void jsonRadioButton_CheckedChanged(object sender, EventArgs e)
		{
			if (initDone && jsonRadioButton.Checked)
			{
				filePathTextBox.Text = "";
				startPara.fileType = "json";
				selectButton.PerformClick();
			}
		}

		// Dxf 格式
		private void dxfRadioButton_CheckedChanged(object sender, EventArgs e)
		{
			if (initDone && dxfRadioButton.Checked)
			{
				filePathTextBox.Text = "";
				startPara.fileType = "dxf";
				selectButton.PerformClick();
			}
		}
		
		// 确定
		private void okButton_Click(object sender, EventArgs e)
		{
			if (filePathTextBox.Text.Trim().Equals(""))
			{
				string msg = "请选择布线文件";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.1");
				}

				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				
				return;
			}
			else
			{
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
		}

		// 取消
		private void cancelButton_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		// 窗体显示后处理
		private void Form_StartAddrMap_Shown(object sender, EventArgs e)
		{
			initDone = true;
		}

		// 预读 Lwf 文件, 检查内容合法性
		public bool preReadLwfFile(string lwfFilePath)
		{
			FileStream fs = null;
			BinaryReader reader = null;
			try
			{
				fs = new FileStream(lwfFilePath, FileMode.Open);
				reader = new BinaryReader(fs);

				// 读取文件头, 解析 bin 区的起始位置和长度
				byte[] header = reader.ReadBytes(0x004F);
				int binStart = header[0x30] << 24 | header[0x31] << 16 | header[0x32] << 8 | header[0x33];
				int binLength = header[0x36] << 24 | header[0x37] << 16 | header[0x38] << 8 | header[0x39];

				// 跳过 bin 区前的数据
				reader.ReadBytes(binStart - 0x004F);

				// 读取 bin 区数据
				byte[] binData = new byte[binLength];
				binData = reader.ReadBytes(binLength);

				int subNumInBin = binData[0x102] << 8 | binData[0x0103];
				int maxValue = 0;
				for (int i = 0; i < subNumInBin; i++)
				{
					int tmpValue = binData[0x1000 + i * 16 + 2] << 8 | binData[0x1000 + i * 16 + 3];
					if (tmpValue > maxValue)
					{
						maxValue = tmpValue;
					}
				}
				int maxLampNumInBin = maxValue;

				return true;
			}
			catch (Exception)
			{
				return false;
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
				if (fs != null)
				{
					fs.Close();
				}
			}
		}

		// 预读 Json 文件, 检查内容合法性
		private bool preReadJsonFile(string jsonFilePath)
		{
			StreamReader sr = null;
			try
			{
				FileInfo info = new FileInfo(jsonFilePath);
				if (!info.Exists)
				{
					return false;
				}

				// 从文件中读取数据
				sr = new StreamReader(new FileStream(jsonFilePath, FileMode.Open));
				StringBuilder sb = new StringBuilder();
				while (true)
				{
					string line = sr.ReadLine();

					if (line == null)
					{
						break;
					}
					else if (line.Trim().Equals(""))
					{
						continue;
					}

					sb.Append(line.Trim());
				}
				string jsonData = sb.ToString();

				// 解析 json
				AddrMapJson addrMapJson = (AddrMapJson)JsonConvert.DeserializeObject(jsonData, typeof(AddrMapJson));

				// 将 addrMapJson 中的数据转化为内部数据结构, 存储在 subInfoList 中, 同时计算统计信息
				bool parseRes = addrMapJson.collectSubInfo();

				// json 解析正常
				if (parseRes == true)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			catch (Exception)
			{
				return false;
			}
			finally
			{
				if (sr != null)
				{
					sr.Close();
				}
			}
		}
	}
}
